package com.example.clinetdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.servicedemo1.IMyAidlInterface;

public class MainActivity extends AppCompatActivity {
    private  ServiceConnection mConn= new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            try {
                //调用时通过AIDL生成的接口内部类Stub的asInterface()方法
                //将IBinder对象转换为IMyAialInterface接口实现对象
                //从而实现调用远程服务接口
                String result=IMyAidlInterface.Stub.asInterface(service).getRemoteData("外部应用数据");
                Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show();
            } catch (RemoteException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }
    private void initView(){
        Button button=findViewById(R.id.butn_bind);
        Button button1=findViewById(R.id.butn_unbind);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent("com.example.aidl.REMOTE_SERVICE");
                intent.setPackage("com.example.servicedemo1");
                bindService(intent,mConn,BIND_AUTO_CREATE);

            }
        });
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unbindService(mConn);
            }
        });
    }
}